<template>
  <div id="user">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="用户昵称">
        <el-input v-model="formInline.user" placeholder="用户昵称"></el-input>
      </el-form-item>
      <el-form-item label="用户角色" prop="roleType">
        <el-select
          v-model="formInline.roleType"
          @change="roleChange"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in role"
            :key="item.rid"
            :label="item.roleName"
            :value="item.roleName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="primary" @click="insetUser">添加</el-button>
         <!-- 导出 -->
          <el-button type="primary" @click="exportUser">导出当前数据</el-button>
         <el-dialog
            title="员工信息"
            :visible.sync="dialoginFormVisible"
            :append-to-body="true"
          >
            <el-form ref="form" :model="insetForm" :rules="rules">
              <el-form-item
                label="用户名"
                :label-width="formLabelWidth"
                :disabled="true"
                prop="userName"
              >
                <el-input
                  v-model="insetForm.userName"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="密码"
                :label-width="formLabelWidth"
                prop="password"
              >
                <el-input
                  type="password"
                  v-model="insetForm.password"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>

              <el-form-item label="性别" :label-width="formLabelWidth">
                <el-select
                  v-model="insetForm.sex"
                  placeholder="性别"
                  style="width: 200px"
                >
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="用户角色"
                prop="roleType"
                :label-width="formLabelWidth"
              >
                <el-select
                  style="width: 200px"
                  v-model="roleForm.roleName"
                  @change="roleChange"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in role"
                    :key="item.rid"
                    :label="item.roleName"
                    :value="item.rid"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="邮箱"
                :label-width="formLabelWidth"
                prop="email"
              >
                <el-input
                  v-model="insetForm.email"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="手机号"
                :label-width="formLabelWidth"
                prop="phone"
              >
                <el-input
                  v-model="insetForm.phone"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
              <el-form-item label="用户昵称" :label-width="formLabelWidth">
                <el-input
                  v-model="insetForm.name"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialoginFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="tianjiaUser('form')">确 定</el-button>
            </div>
          </el-dialog>
         
      </el-form-item>
    </el-form>

    <!-- 表格数据 -->
    <el-table id="exportTable" :data="tableData" border style="width: 100%">
      <el-table-column fixed prop="uid" label="id" width="150">
      </el-table-column>
      <el-table-column prop="userName" label="用户名" width="120">
      </el-table-column>
      <el-table-column
        prop="password"
        label="密码"
        width="120"
      ></el-table-column>
      <el-table-column prop="sex" label="性别" width="120"> </el-table-column>
      <el-table-column prop="role.roleName" label="用户角色" width="120">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="170"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
      </el-table-column>
      <!-- <el-table-column prop="this.statusName" label="用户状态" width="120">
      </el-table-column> -->
      <el-table-column prop="phone" label="用户手机号" width="120">
      </el-table-column>
      <el-table-column prop="name" label="用户昵称" width="120">
      </el-table-column>
      <!-- <el-table-column prop="adminIstrators" label="是否管理员" width="120">
      </el-table-column> -->
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="medium"
            >删除</el-button
          >
          <!-- <el-button type="text" @click="updateUser(scope.row)"  size="small" >编辑</el-button> -->
          <el-button type="text" @click="updateUser(scope.row)">编辑</el-button>
          <el-dialog
            title="员工信息"
            :visible.sync="dialogFormVisible"
            :append-to-body="true"
          >
            <el-form ref="form" :model="form" :rules="rules">
              <el-form-item
                label="用户名"
                :label-width="formLabelWidth"
                :disabled="true"
                prop="userName"
              >
                <el-input
                  v-model="form.userName"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="密码"
                :label-width="formLabelWidth"
                prop="password"
              >
                <el-input
                  type="password"
                  v-model="form.password"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>

              <el-form-item label="性别" :label-width="formLabelWidth">
                <el-select
                  v-model="form.sex"
                  placeholder="性别"
                  style="width: 200px"
                >
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="用户角色"
                prop="roleType"
                :label-width="formLabelWidth"
              >
                <el-select
                  style="width: 200px"
                  v-model="roleForm.roleName"
                  @change="roleChange"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in role"
                    :key="item.rid"
                    :label="item.roleName"
                    :value="item.rid"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="邮箱"
                :label-width="formLabelWidth"
                prop="email"
              >
                <el-input
                  v-model="form.email"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="手机号"
                :label-width="formLabelWidth"
                prop="phone"
              >
                <el-input
                  v-model="form.phone"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
              <el-form-item label="用户昵称" :label-width="formLabelWidth">
                <el-input
                  v-model="form.name"
                  autocomplete="off"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="updateOneUser('form')">确 定</el-button>
            </div>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>
    <!-- @current-change 事件（当前页改变时触发） @size-change 每条页数改变时触发|| page-size 每页显示多少条数据  || current-page当前页    -->
    <el-pagination
      small
      @current-change="clickcurrentChange"
      :page-size="pageSize"
      :current-page="pageNum"
      layout="prev, pager, next"
      :total="total"
    >
    </el-pagination>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleForm: {
        roleName: "",
      },
      formInline: {
        user: "",
        //下拉框选中的值
        roleType: "",
      },
      //角色列表
      role: [],
      //表格数据
      tableData: [],
      //编辑弹出框输入框
      form: {
        uid: "",
        userName: "",
        password: "",
        sex: "",
        rid: "",
        email: "",
        phone: "",
        name: "",
      },
      //添加弹出输入框
      insetForm: {
        uid: "",
        userName: "",
        password: "",
        sex: "",
        rid: "",
        email: "",
        phone: "",
        name: "",
      },
      rules: {
        userName: [
          { required: true, message: "请填写用户名！", trigger: "blur" },
          { min: 5, max: 20, message: "用户名在5-20之间", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请填写密码！", trigger: "blur" },
          { min: 5, max: 20, message: "密码在5-20之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern:
              /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g,
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          // 这个只能验证手机号
          // { pattern:/^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/, message: "请输入合法手机号", trigger: "blur" }
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
            message: "请输入合法手机号/电话号",
            trigger: "blur",
          },
        ],
      },
      dialogFormVisible: false,
      dialoginFormVisible : false,
      formLabelWidth: "120px",
      //总数量
      total: "",
      //当前页数
      pageNum: 1,
      // 每页显示的条数
      pageSize: 1,
    };
  },
  async created() {
    this.getUser(
      this.pageNum,
      this.pageSize,
      this.formInline.user,
      this.formInline.roleType
    );
    this.getRole();
  },

  methods: {
    // 角色下拉框改变时触发
    roleChange() {
      console.log(this.formInline.roleType);
    },
    //查询按钮
    onSubmit(role) {
      this.getUser(
        this.pageNum,
        this.pageSize,
        this.formInline.user,
        this.formInline.roleType
      );
    },
    //删除
    handleClick(row) {
      //拿到要删除的用户id
      const uid = row.uid;
      const user = JSON.parse(sessionStorage.getItem("user"));
      if (user.data.role.rid != 1) {
        this.$message.error("你没有此权限，请联系管理员");
        return;
      }
      if (row.role.rid == 1) {
        this.$message.error("不能删除系统管理员");
        return;
      }
      this.$axios({
        method: "post",
        url: "user/delUser",
        data: { uid: uid },
      }).then((res) => {
        console.log(res.data.code);
        //回调函数
        if (res.data.code == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getUser(
            this.pageNum,
            this.pageSize,
            this.formInline.user,
            this.formInline.roleType
          );
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    //编辑按钮
    updateUser(row) {
      //弹窗开启
      this.dialogFormVisible = true;
      this.form.uid = row.uid;
      this.form.userName = row.userName;
      this.form.password = row.password;
      this.form.sex = row.sex;
      this.form.email = row.email;
      this.form.phone = row.phone;
      this.form.name = row.name;
      this.roleForm.roleName = row.role.rid;
    },
    //修改确定按钮
    updateOneUser(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.form.rid = this.roleForm.roleName;
          console.log(this.form);
          this.$axios({
            url: "user/updateUser",
            method: "post",
            data: {
              uid: this.form.uid,
              userName: this.form.userName,
              password: this.form.password,
              sex: this.form.sex,
              rid: this.form.rid,
              email: this.form.email,
              phone: this.form.phone,
              name: this.form.name,
            },
          }).then((res) => {
            console.log(res);
            if (res.data.code) {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              //弹窗关闭
              this.dialogFormVisible = false;
              this.getUser(
                this.pageNum,
                this.pageSize,
                this.formInline.user,
                this.formInline.roleType
              );
            } else {
              this.message.error("修改失败");
            }
          });
        }
      });
    },
    // 点击添加按钮打开输入框
    insetUser(){
        this.dialoginFormVisible = true
        this.insetForm.sex = ""
        this.insetForm.userName = ""
        this.insetForm.password = ""
        this.insetForm.email = ""
        this.insetForm.phone = ""
        this.insetForm.name = ""
        this.roleForm.roleName = ""
        // console.log(this.insetForm.userName)
        // this.insetForm.userName = ""
        // this.roleForm.roleName = ""
        // console.log(this.insetForm.password)
        // console.log(this.insetForm.sex)
        // console.log(this.insetForm.email)
        // console.log(this.insetForm.phone)
        // console.log(this.insetForm.name)
        //  this.insetForm.rid = this.roleForm.roleName 
        // console.log(this.insetForm.rid)
    },
    //确定添加按钮
    tianjiaUser(name){
      this.$refs[name].validate((valid)=>{
          if(valid){
            this.insetForm.rid = this.roleForm.roleName
              this.$axios({
                method : "post",
                url : "user/insertUser",
                data :{
                  userName : this.insetForm.userName,
                  password : this.insetForm.password,
                  sex : this.insetForm.sex,
                  email : this.insetForm.email,
                  phone : this.insetForm.phone,
                  name : this.insetForm.name,
                  rid : this.insetForm.rid
                },
              }).then(res=>{
                  if(res.data.code){
                    this.$message({
                      message: "修改成功",
                      type: "success",
                    });
                    this.dialoginFormVisible = false;
                    this.getUser(
                      this.pageNum,
                      this.pageSize,
                      this.formInline.user,
                      this.formInline.roleType
                    );
                  }else{
                    this.$message.error("添加失败")
                    this.dialoginFormVisible = false;
                  }
              })
          }
      })

    },
    //查询用户列表
    getUser(pageNum, pageSize, name, roleType) {
      this.$axios({
        method: "post",
        url: "user/oneUser",
        data: {
          pageNum: pageNum,
          pageSize: pageSize,
          name: name,
          roleName: roleType,
        },
      }).then((res) => {
        this.tableData = res.data.data.list;
        this.total = res.data.data.total;
      });
    },
    //查询角色列表
    getRole() {
      this.$axios({
        method: "post",
        url: "role/roles",
      }).then((res) => {
        this.role = res.data.data;
        console.log(this.role);
      });
    },
    //当前页 事件
    clickcurrentChange(val) {
      this.pageNum = val;
      this.getUser(
      this.pageNum,
      this.pageSize,
    );
      console.log(val);
    },
    // 导出按钮
    exportUser() {
      this.$axios({
        method: "post",
        url: "user/exPortUser",
        data: { user: this.tableData },
        responseType: "blob",
      })
        .then((res) => {
          //将文件流转成blob形式
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          let filename = "员工信息.xls";
          //创建一个超链接，将文件流赋进去，然后实现这个超链接的单击事件
          const elink = document.createElement("a");
          elink.download = filename;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        })
        .catch((error) => {
          this.$message.error("导出失败");
        });
      console.log(this.tableData);
    },
  },
};
</script>